<?php

if (strpos ($_SERVER['PHP_SELF'], 'functions_autotag.inc') !== false) {
    die ('This file can not be used on its own.');
}

$dummy=assistfb_setPageInfoCookie();

// +-----------+
// | 専用関数  |
// +-----------+
// +---------------------------------------------------------------------------+
function assistfb_setPageInfoCookie(
) {
	$rt=assistfb_getSignedRequest();
	if ($rt['page']['id']<>""){
		$cooktime = COM_getUserCookieTimeout();
        if ($cooktime > 0) {
			$expire=time() + $cooktime;
			SEC_setCookie("fb_pageid",$rt['page']['id'],$expire);
			SEC_setCookie("fb_admin",$rt['page']['admin'],$expire);
			SEC_setCookie("fb_liked",$rt['page']['liked'],$expire);
		}
	}
	return;
}
function assistfb_getPageInfoCookie(
) {
	
}
// +---------------------------------------------------------------------------+
// | 機能 Get the current signed request being used by the SDK
// | 書式 $rt=assistfb_getSignedRequest();
// | 書式 $rt=assistfb_getSignedRequest($appid,$secret);
// +---------------------------------------------------------------------------+
// | 引数 $appid:Application ID 省略時 Facebook OAuth Application ID
// | 引数 $secret:Application Secret 省略時Facebook OAuth Application Secret
// +---------------------------------------------------------------------------+
// | 戻値 : $rt['err']:エラーが発生した場合エラーメッセージ
// | 		アプリがページのタブでIFRAMEロードされた場合
// |			$rt['page']['id']:
// |			$rt['page']['admin']:
// |			$rt['page']['liked']:
// |
// |		他　user algorithm issued_at user_id oauth_token expires app_data
// |		profile_id
// +---------------------------------------------------------------------------+
// 20111129
function assistfb_getSignedRequest(
	$assist=""
	,$secret=""
) {
	global $_CONF;
	global $_ASSISTFB_CONF;
	
	$rt=array();
	
	if  (!file_exists($_ASSISTFB_CONF['facebook_phpsdk'].'facebook.php')) {
		COM_errorLog("[assistfb] function facebook not exist " ,1);
		$rt["err"]="function facebook not exist";
		$rt["page"]["admin"]=0;
		return $rt;
	}
	
	if ($appid==""){
		$appid = $_CONF['facebook_consumer_key'];
		$secret = $_CONF['facebook_consumer_secret'];
	}
	$facebook_conf = array();
	$facebook_conf['appId'] = $appid;
	$facebook_conf['secret'] = $secret;
	$facebook_conf['fileUpload'] = false;
	$facebook = new Facebook($facebook_conf);
	
	try {
		$signed_request = $facebook->getSignedRequest();
		$rt=$signed_request;
	} catch (FacebookApiException $e) {
		error_log($e);
		COM_errorLog("[assistfb] getSignedRequest ".$e ,1);
		$rt["err"]=$e;
	}
	
	return $rt;
	
}


// +---------------------------------------------------------------------------+
// | 機能 ログインリンク取得
// | 書式 assistfb_getloginlink()
// | 書式 assistfb_getloginlink('yes')
// +---------------------------------------------------------------------------+
// | 引数 $logoutlink:ログアウトリンクを表示するかどうか yes YES の場合表示
// | 引数 $pageadminonly:ログアウトリンクを表示するかどうか yes YES の場合表示
// +---------------------------------------------------------------------------+
// | 戻値 : ログインしていない時　facebook oauth ログインリンク
// | 		　ただしページ管理者のみの場合はIFRAMEロードページの管理者の場合
// |		ログインしている時　ログアウトリンク
// |		　ただしログアウトリンクを表示する設定の場合
// +---------------------------------------------------------------------------+
// 20111129
function assistfb_getloginlink(
	$logoutlink=""
	,$pageadminonly="YES"
)
{
	global $_CONF;
	global $_USER;
	global $LANG01;
	
	//引数チェック
	if (strtoupper($logoutlink)==="YES"){
		$logoutlink=true;
	}else{
		$logoutlink=false;
	}
	if (strtoupper($pageadminonly)==="YES"){
		$pageadminonly=true;
	}else{
		$pageadminonly=false;
	}
	
	$return ="";
	
	//ログインしていない時
	if( COM_isAnonUser() ) {
		$sr=assistfb_getSignedRequest();
		//IFRAMEロードされたページの管理者の場合 または
		if  ($sr['page']['admin'] OR $pageadminonly==false){
			$return = assistfb_loginform_oauth("facebook");
		}
	//ログインしている時
	//facebook oauthでログインしているとはかぎりません
	}else{
		//ログアウトリンクを表示する時
		if ($logoutlink){
			$url = $_CONF['site_url'] . '/users.php?mode=logout';
            $url = COM_buildUrl( $url );
            $link= COM_createLink($LANG01[19], $url);
			$return = $link;
		}
	}
	return $return;
}

// +---------------------------------------------------------------------------+
// | 機能 ログインリンク取得
// | 書式 assistfb_loginform_oauth('facebook')
// +---------------------------------------------------------------------------+
// | 引数 $service:oauthservice
// +---------------------------------------------------------------------------+
// | 戻値 : ログインリンク
// +---------------------------------------------------------------------------+
// 20111129
function assistfb_loginform_oauth(
	$service
)
{
    global $_CONF;
	
	$return="";
	
	if ($_CONF[$service.'_login']){
        $login = COM_newTemplate($_CONF['path_layout']);
		$login->set_file('oauth_login', 'loginform_oauth.thtml');
		$login->set_var('oauth_service', $service);
		// for sign in image
		$login->set_var('oauth_sign_in_image', $_CONF['site_url'] 
			. '/images/login-with-' . $service . '.png');
		$login->set_var('oauth_sign_in_image_style', '');
		$login->parse('output', 'oauth_login');
	
		$return= $login->finish($login->get_var('output'));
	}
	
	return $return;

}

// +---------------------------------------------------------------------------+
function assistfb_getUserInfo(
	$item=""
	,$user=""
	,$assist=""
	,$secret=""
) {
	global $_CONF;
	global $_USER;
	
	if ($user===""){
		if  ($_USER["remoteusername"]<>""
			AND $_USER["remoteservice"]==="oauth.facebook"){
			$user = $_USER["remoteusername"];
		}else{
			return null;
		}
	}
	
	if ($appid==""){
		$appid = $_CONF['facebook_consumer_key'];
		$secret = $_CONF['facebook_consumer_secret'];
	}
	
	$facebook_conf = array();
	$facebook_conf['appId'] = $appid;
	$facebook_conf['secret'] = $secret;
	$facebook_conf['fileUpload'] = false; // 
	
	$facebook = new Facebook($facebook_conf);
	
	
	$arg = array();
	$arg['method'] = 'users.getInfo';
	$arg['uids'] = $user;
	$arg['fields'] = 'username';
	
	try {
		$info = $facebook->api($arg);
		echo "uid=".$info[0]["uid"]."<br>";
		echo "name=".$info[0]["username"]."<br>";
		$usernmae=$info[0]["username"];
		if ($username===""){
			return null;
		}	
	} catch (FacebookApiException $e) {
		error_log($e);
		echo $e;
		return null;
	}
	//
	
	try {
		$user_profile = $facebook->api('/'.$username);
	} catch (FacebookApiException $e) {
		error_log($e);
		echo $e;
		return null;
	}
	
	if ($item==""){
		$return=assistfb_userprofile($user_profile);		
	}else{
		switch( $item ) {
			case 'user_id':
				$return=$user_profile['location']['id'];
				break;
			case 'name':
			case 'first_name':
			case 'last_name':
			case 'link':
			case 'username':
			case 'gender':
			case 'email':
			case 'timezone':
			case 'locale':
			case 'verified':
			case 'updated_time':
				$return=$user_profile[$item];
				break;
			case 'location_id':
				$return=$user_profile['location']['id'];
			case 'location_name':
				$return=$user_profile['location']['name'];
				break;
			case 'language_id':
				$return=$user_profile['languages'][0]['id	'];
				break;
			case 'language_name':
				$return=$user_profile['languages'][0]['name'];
				break;
			case 'isPageAdmin':
				break;
		}
	}
	
	return $return;
	
}


// +---------------------------------------------------------------------------+
function assistfb_userprofile (
	$user_profile
) {
	$rt=array();
	if (is_array($user_profile)){
		foreach( $user_profile as $nm => $value ){
			if (is_array($user_profile[$nm])){
				$wkary2=$user_profile[$nm];
				foreach( $wkary2 as $nm2 => $value2 ){
					if (is_array($wkary2[$nm2])){
						$wkary3=$wkary2[$nm2];
						foreach( $wkary3 as $nm3 => $value3 ){
							if  (is_array($wkary3[$nm3])){
								$wkary4=$wkary3[$nm3];
								foreach( $wkary4 as $nm4 => $value4 ){
									//echo "A=".$nm."=".$nm2."=".$nm3."=".$nm4."=".$value4."<br>";
									$rt[$nm."_".$nm2."_".$nm3."_".$nm4]=$value4;
								}
							}else{	
								//echo "B=".$nm."=".$nm2."=".$nm3."=".$value3."<br>";
								$rt[$nm."_".$nm2."_".$nm3]=$value3;
							}
						}
					}else{	
						//echo "C=".$nm."=".$nm2."=".$value2."<br>";
						$rt[$nm."_".$nm2]=$value2;
					}
				}
			}else{	
				//echo $nm."=".$value."<br>";
				$rt[$nm]=$value;
			}
		}
    }
	return $rt;
}

// +---------------------------------------------------------------------------+
function assistfb_getPageInfo(
	$item=""
	,$user=""
	,$assist=""
	,$secret=""
) {
	global $_CONF;
	global $_USER;
	
	$rt=array();
	
	if ($user===""){
		if  ($_USER["remoteusername"]<>""
			AND $_USER["remoteservice"]==="oauth.facebook"){
			$user = $_USER["remoteusername"];
		}else{
			$rt["err"]="user error";
			return $rt;
		}
	}
	
	if ($appid==""){
		$appid = $_CONF['facebook_consumer_key'];
		$secret = $_CONF['facebook_consumer_secret'];
	}
	
	$facebook_conf = array();
	$facebook_conf['appId'] = $appid;
	$facebook_conf['secret'] = $secret;
	$facebook_conf['fileUpload'] = false; // 
	
	$facebook = new Facebook($facebook_conf);
	
	$access_token = $_COOKIE['request_token'];
	$facebook->setAccessToken($access_token);
	
	
	$pp ="name";// - Page entered profile field. May not be blank.
    $pp.=",page_url";// - Page URL. May not be blank.
	$pp.=",pic_small";// - URL of profile picture
						//, with max width 50px and max height 150px. May be blank.
	$pp.=",pic_square";// - URL of a square section of the profile picture
						//, with width 50px and height 50px. May be blank.
	$pp.=",pic_big";// - URL of profile picture with max width 200px and max height 600px. 
					//May be blank.
	$pp.=",pic";// - URL of profile picture with max width 100px and max height 300px. 
				//May be blank.
	$pp.=",pic_large";// - URL of profile picture with max width 396px and max height 1188px. 
				//May be blank.
    $pp.=",type";// - Contains the type of the page.
    $pp.=",website";// - Contains the website of the page.
	
	
	//$pp.=",location";//**location ** - Contains the location of the entity. 
					//Applies to Local Businesses. Contains five children: 
					// street, city, state, country, zip **. Notes on each othe 
//	$pp.=",street";// may be blank; 
//	$pp.=",city ";// may be blank; 
//	$pp.=",state ";// is a well-defined two-letter American state or Canadian province abbreviation, and may be blank; 
//	$pp.=",country";// is well-defined, and may be blank; 
//	$pp.=",zip";// is an integer, and is 0 if unspecified.
	
	//$pp.=",hours";//- Contains the operating hours. 
		//Each local business will be allowed to specify up to two sets of operating hours per day. 
		//	Contains the following children, 
//	$pp.=",mon_1_open,mon_1_close"; 
//	$pp.=",tue_1_open,tue_1_close"; 
//	$pp.=",wed_1_open,wed_1_close"; 
//	$pp.=",thu_1_open,thu_1_close"; 
//	$pp.=",fri_1_open,fri_1_close"; 
//	$pp.=",sat_1_open,sat_1_close"; 
//	$pp.=",sun_1_open,sun_1_close"; 
//	$pp.=",mon_2_open,mon_2_close"; 
//	$pp.=",tue_2_open,tue_2_close"; 
//	$pp.=",wed_2_open,wed_2_close"; 
//	$pp.=",thu_2_open,thu_2_close"; 
//	$pp.=",fri_2_open,fri_2_close"; 
//	$pp.=",sat_2_open,sat_2_close"; 
//	$pp.=",sun_2_open,sun_2_close";
        //Each field is returned with time (in seconds since epoch). For example, 9:00 AM is represented as 406800
	
	$pp.=",band_members";// - Members of the band, may be blank.
    $pp.=",bio";// - biography field, may be blank.
    $pp.=",hometown";// - hometown field, may be blank.

	//$pp.=",page_url";// - genre of music. Contains the following children: 
//	$pp.=",dance, party,relax,talk,think,workout,sing,intimate,raunchy,headphones";
			//Notes on the children:
			//Zero or more of them may be set
			//May be 1 or 0.
	
	$pp.=",record_label";// - record label, may be blank
    $pp.=",influences";// - influences, may be blank
    $pp.=",has_added_app";// - Bool (0 or 1) indicating whether the page has added the calling application to their Facebook account.
    $pp.=",founded";// - When company was founded, may be blank
    $pp.=",company_overview";// - overview of company, may be blank
    $pp.=",mission";// - Mission of company, may be blank
    $pp.=",products ";// - Company's products, may be blank
    $pp.=",release_date";// - Release date of film, may be blank
    $pp.=",starring";// - Who's starring in TV/Film, may be blank
    $pp.=",written_by";// - Who wrote TV/Film, may be blank
    $pp.=",directed_by";// - Who directed TV/Film, may be blank
    $pp.=",produced_by";// - Who produced TV/Film, may be blank
    $pp.=",studio";// - Studio Film was produced, may be blank
    $pp.=",awards";// - Awards received by TV/Film, may be blank
    $pp.=",plot_outline";// - Plot outline of TV/Film, may be blank
    $pp.=",network";// - Network of TV show, may be blank
    $pp.=",season";// - Season of TV show, may be blank
    $pp.=",schedule";// - Schedule of TV show, may be blank
    $pp.=",fan_count";// - The number of users who are fans or supporters of this Page. This field may be blank.

	
	//echo "pp=".$pp;
	//echo "-----<br>";
	$arg = array();
	$arg['method'] = 'pages.getInfo';
	$arg['fields'] = $pp;//
	$arg['access_token'] = $access_token;
	
	try {
		$info = $facebook->api($arg);
		
		//
		//$rt["page_id"]=$info[0]["page_id"];
		//$rt["name"]=$info[0]["name"];
		$ary=$info[0];
		foreach( $ary as $nm => $value ){
			//echo $nm."=".$value."<br>";
			$rt[$nm]=$value;
		};

		
		
		
	} catch (FacebookApiException $e) {
		error_log($e);
		$rt["err"]=$e;
		return $rt;
	}
	
	return $rt;
	
}

// +---------------------------------------------------------------------------+
function assistfb_getAppProperties(
	$appid=""
	,$secret=""
) {
	
	global $_CONF;
	
	$rt=array();
	
	if ($appid==""){
		$appid = $_CONF['facebook_consumer_key'];
		$secret = $_CONF['facebook_consumer_secret'];
	}
	
	$facebook_conf = array();
	$facebook_conf['appId'] = $appid;
	$facebook_conf['secret'] = $secret;
	$facebook_conf['fileUpload'] = false; // 
	
	$facebook = new Facebook($facebook_conf);
	
	
	$arg = array();
	$arg['method'] = 'admin.getAppProperties';
	//$arg['access_token'] = $_COOKIE['request_token'];
	
	
	
	$pp ="about_url";
	$pp.=",app_id";
	$pp.=",authorize_url";
	$pp.=",base_domain";
	$pp.=",base_domains";
	
	$pp.=",callback_url";
	$pp.=",canvas_name";
	$pp.=",connect_logo_url";
	$pp.=",connect_preview_template";
	$pp.=",connect_reclaim_url";
	$pp.=",connect_url";
	$pp.=",contact_email";
	$pp.=",creator_uid";
	$pp.=",dashboard_url";
	$pp.=",default_column";
	$pp.=",description";
	$pp.=",desktop";
	$pp.=",dev_mode";
	$pp.=",edit_url";
	$pp.=",email";
	$pp.=",help_url";
	$pp.=",icon_url";
	$pp.=",iframe_enable_util";
	$pp.=",ignore_ip_whitelist_for_ss";
	$pp.=",info_changed_url";
	$pp.=",installable";
	$pp.=",ip_list";
	
	$pp.=",is_mobile";
	$pp.=",locale";
	$pp.=",logo_url";
	$pp.=",message_action";
	$pp.=",post_authorize_redirect_url";
	$pp.=",preload_fql";
	$pp.=",preload_fql_multiquery";
	$pp.=",privacy_url";
	
	$pp.=",private_install";
	$pp.=",profile_tab_url";
	$pp.=",publish_action";
	$pp.=",publish_self_action";
	$pp.=",publish_self_url";
	$pp.=",publish_url";
	
	//$pp.=",quick_transitions";
	$pp.=",secure_callback_url";
	$pp.=",secure_page_tab_url";
	
	$pp.=",support_url";
	$pp.=",tab_default_name";
	$pp.=",targeted";
	$pp.=",tos_url";
	$pp.=",uninstall_url";
	$pp.=",use_iframe";
	$pp.=",video_rentals";
	
	$arg['properties'] = $pp;
	
	try { 
		$api = $facebook->api($arg);
		//echo "api=".$api."<br>";
		$w=rtrim(ltrim($api,"{"),"}");
		$apiary=explode(',',$w);
		$ary=array();
		foreach( $apiary as $nm => $value ){
			$wary=explode(':',$value);
			$rt[ltrim(rtrim($wary[0],'"'),'"')]=ltrim(rtrim($wary[1],'"'),'"');
		}
	} catch (FacebookApiException $e) {
		error_log($e);
		echo "err=".$e."<br>";
		$rt['err']=$e;
	}	
	
	

	return $rt;
	
}

// +---------------------------------------------------------------------------+
// | 機能  テンプレートフォルダパスを取得
// | 書式 assistfb_templatePath('data','default','databox')
// +---------------------------------------------------------------------------+
// | 引数 $kind:'data' 'category' ''newlist' 'admin'
// | 引数 $template:  'default'
// | 引数 $pi_name: 'databox' 'userbox' 'formbox'
// +---------------------------------------------------------------------------+
// | 戻値 :テンプレートフォルダパス
// +---------------------------------------------------------------------------+
// 20101227 copy from functions_databox.php
function assistfb_templatePath (
    $kind = 'data'
    ,$template ='default'
    ,$pi_name= 'assitfb'
    )
{

    global $_CONF;

    if (is_null($template) OR ($template==="")){
        $template="default";
    }

    if (is_null($pi_name)){
        $pi_name="databox";
    }

    $box_conf="_".strtoupper($pi_name)."_CONF";
    global $$box_conf;
    $box_conf=$$box_conf;


    if ($kind==="admin"){
        $conf_templates=$box_conf["templates_admin"];
    }else{
        $conf_templates=$box_conf["templates"];
    }



    //"standard";//標準テンプレートを使用する
    //"custom";//カスタムテンプレートを使用する
    //"theme";//テーマテンプレートを使用する
    if  ($conf_templates==="theme"){

        $tmplfld=$_CONF['path_layout'] .$box_conf['themespath'].$kind;
        if ($kind<>"admin"){

            $tmplfld.="/".$template;
        }

        if (is_dir($tmplfld)) {

        }else{

            $tmplfld=$_CONF['path'] .'plugins/'.$pi_name.'/templates/'.$kind;
            if ($kind<>"admin"){
                $tmplfld.="/default";
            }
        }

    }else if  ($conf_templates==="custom"){

        $tmplfld=$_CONF['path'] .'plugins/'.$pi_name.'/custom/templates/'.$kind;

        if ($kind<>"admin"){

            $tmplfld.="/".$template;

        }

        if (is_dir($tmplfld)){

        }else{

            $tmplfld=$_CONF['path'] .'plugins/'.$pi_name.'/templates/'.$kind;
            if ($kind<>"admin"){

                $tmplfld.="/default";

            }
        }
    }else{

        $tmplfld=$_CONF['path'] .'plugins/'.$pi_name.'/templates/'.$kind;
        if ($kind<>"admin"){

            $tmplfld.="/default";
        }

    }


    return $tmplfld;
}

//==============================================================================
// +---------------------------------------------------------------------------+
// | 自動タグ
// | 書式 plugin_autotags_assistfb ($op, $content, $autotag)
// +---------------------------------------------------------------------------+
// 
function plugin_autotags_assistfb (
    $op
    , $content = ''
    , $autotag = ''
){
	
    //Option Display
    if ($op == 'tagname' ) {
        $tagname[]='assistfb';
        return $tagname;
    } else if ($op == 'parse') {
        //引数チェック
        $p1 = COM_applyFilter ($autotag['parm1']);
        $p2 = COM_applyFilter ($autotag['parm2']);
        $tag = COM_applyFilter ($autotag['tag']);
        $tagstr = COM_applyFilter ($autotag['tagstr']);

        //各処理
        switch( $tag ) {
            case 'assistfb' :
                $p=assistfb_parm2($p2);
                switch($p1) {
                    case 'loginlink_pageadminonly' :
						$rt=assistfb_getloginlink(
							$p['logoutlink']);
                        break;
                    case 'loginlink' :
						$rt=assistfb_getloginlink(
							$p['logoutlink'],"");
                        break;
                }

                $content = str_replace ($autotag['tagstr'], $rt, $content);
                return $content;
                break;

        }
    }
}

//第二引数分割
function assistfb_parm2 ($p2)
{
    $ary=array();
    $px = explode (' ', trim ($p2));
    if (is_array ($px)) {
        foreach ($px as $part) {
            $a = explode (':', $part);
            $ary["{$a[0]}"]=$a[1];
        }
    }
    return $ary;

}

?>
